package com.carl.zlds.service.impl;

import com.carl.zlds.tool.util.AssertUtil;
import com.carl.zlds.tool.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carl.zlds.dao.GameMapper;
import com.carl.zlds.model.Game;
import com.carl.zlds.pojo.dto.SaveGameDTO;
import com.carl.zlds.pojo.vo.GameTagVO;
import com.carl.zlds.pojo.vo.GameVO;
import com.carl.zlds.pojo.vo.GameWithTagVO;
import com.carl.zlds.service.IGameService;
import com.carl.zlds.service.IGameTagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author carl
 */
@Slf4j
@Service
public class GameServiceImpl extends ServiceImpl<GameMapper, Game> implements IGameService {

    @Autowired
    private IGameTagService gameTagService;

    @Override
    public void saveGame(Long id, SaveGameDTO dto) {
        Game game;
        if (id > 0) {
            Wrapper<Game> wrapper = new QueryWrapper<Game>().eq("id", id).eq("weight", 0);
            game = this.baseMapper.selectOne(wrapper);
            AssertUtil.isNull("游戏不存在", game);
            game.setStatus(dto.getStatus());
        } else {
            game = new Game();
            game.setStatus(1);
        }

        game.setName(dto.getName());
        game.setImg(dto.getImg());
        game.setUrl(dto.getUrl());

        if (id > 0) {
            this.baseMapper.updateById(game);
        } else {
            this.baseMapper.insert(game);
        }
    }

    @Override
    public void deleteGame(Long id) {
        Wrapper<Game> wrapper = new QueryWrapper<Game>().eq("id", id).eq("weight", 0);
        Game game = this.baseMapper.selectOne(wrapper);
        AssertUtil.isNull("游戏不存在", game);

        game.setWeight(-1);
        this.baseMapper.updateById(game);
    }

    @Override
    public List<GameVO> getGameList() {
        Wrapper<Game> wrapper = new QueryWrapper<Game>().ge("weight", 0);
        List<Game> gameList = this.baseMapper.selectList(wrapper);
        return ObjUtil.processModelList(gameList, GameVO.class);
    }

    @Override
    public List<GameWithTagVO> getGameListWithTag() {
        List<GameVO> gameList = getGameList();
        List<GameWithTagVO> gameWithTagList = ObjUtil.processModelList(gameList, GameWithTagVO.class);
        for (GameWithTagVO item : gameWithTagList) {
            List<GameTagVO> list = gameTagService.getGameTagList(item.getId());
            item.setTagList(list);
        }
        return gameWithTagList;
    }
}
